package zju.dgm.service.region;

import zju.dgm.dto.*;
import zju.dgm.util.Serializer;
import zju.dgm.util.SyncUtil;

import java.util.Map;
import java.util.List;

public class RegionDataHelper {
    // DataFrame过滤器
    // MasterListener过滤器
    public class MasterFilter implements DFFilter {
        @Override
        public boolean isWanted(DataFrame df) {
            if (df == null)
                return false;
            switch (df.getType()){
                case DataFrame.MASTER_MAP_REQ:
                case DataFrame.MASTER_VERSION_REQ:
                case DataFrame.MASTER_FREE_REQ:
                case DataFrame.MASTER_ADD_REQ:
                case DataFrame.MASTER_DELETE_REQ:
                    return df.getSender()!=null;
            }
            return false;
        }
    }
    public final MasterFilter masterFilter = new MasterFilter();

    // ServerListener过滤器
    public class ServerFilter implements DFFilter {
        @Override
        public boolean isWanted(DataFrame df) {
            if (df == null)
                return false;
            switch (df.getType()){
                case DataFrame.LOG_REQ:
                case DataFrame.LOG_INFO:
                    return df.getSender()!=null;
            }
            return false;
        }
    }
    public final ServerFilter serverFilter = new ServerFilter();


    // DataFrame与Java类型转换函数
    // String转DataFrame
    public DataFrame strToData(String name, int type) {
        DataFrame data = new DataFrame(SyncUtil.serverInfo.getName(), type, Serializer.getBytesFromObject(name));
        return data;
    }
    // Map转DataFrame
    public DataFrame mapToData(Map<String, List<ServerInfo>> map, int type) {
        DataFrame data = new DataFrame(SyncUtil.serverInfo.getName(), type, Serializer.getBytesFromObject(map));
        return data;
    }
    // serverList转DataFrame
    public DataFrame listToData(List<ServerInfo> list, int type) {
        DataFrame data = new DataFrame(SyncUtil.serverInfo.getName(), type, Serializer.getBytesFromObject(list));
        return data;
    }


    // DataFrame转String
    public String dataToString(DataFrame data) {
        return Serializer.getObjectFromBytes(data.getData(), String.class);
    }
    // DataFrame转Map
    public Map<String, List<ServerInfo>> dataToMap(DataFrame data) {
        return Serializer.getObjectFromBytes(
                data.getData(),
                new MyTR<Map<String, List<ServerInfo>>>(){}
        );

    }
    // DataFrame转list
    public List<ServerInfo> dataToList(DataFrame data) {
        return Serializer.getObjectFromBytes(
                data.getData(),
                new MyTR<List<ServerInfo>>(){}
        );
    }

}
